<template>
    <form class="validate-form-container">
        <!-- 默认插槽 -->
        <slot name="default"></slot>
        <!-- 阻止默认行为 -->
        <div class="submit-area" @click.prevent="submitForm">
            <!-- 具名插槽 -->
            <slot name="submit">
                <button type="submit" class="btn btn-primary">提交</button>
            </slot>
        </div>
    </form>
</template>

<script lang='ts'>
import {defineComponent,reactive,ref,onUnmounted} from 'vue'
// 引入mitt库，并调用mitt函数
import mitt from 'mitt'
export const emitter = mitt()
// 定义错误函数的类型
type ValidateFun = ()=> boolean
export default defineComponent({
    components:{
    },
    // 暴露事件，因为不需要数据的校验，可以使用数组的方式
    emits: ['form-submit'],
    setup(props,context) {
        // 定义错误信息，因为有多个错误信息，采用数组存放
       let funArr:ValidateFun[] = []
       const submitForm = () => {
           console.log(funArr.map(func => func()))
          const result = funArr.map(func => func()).every(result => result)
          context.emit('form-submit',result)
       }
       
       const callback = (func?:ValidateFun) => {
           console.log('监听：',func);
           if (func) {
               funArr.push(func)
           }
       }

        emitter.on('form-item-created',callback)
        onUnmounted(() => {
            emitter.off('form-item-created',callback)
            funArr = []
        })

        return {
            submitForm
        }
    }
})
</script>

<style>

</style>